<?php

namespace app\api\controller;

use think\facade\Log;
use think\Response;

/**
 * 兼容版本的API基础控制器
 */
class Base extends \app\BaseController
{
    /**
     * 当前用户信息
     * @var object|null
     */
    protected $userInfo;

    /**
     * 当前用户Token
     * @var string
     */
    protected $token;

    /**
     * 初始化方法
     */
    protected function initialize(): void
    {
        parent::initialize();
        
        // 获取用户信息（由JWT中间件设置）
        $this->userInfo = $this->request->userInfo ?? null;
        $this->token = $this->request->token ?? '';
    }

    /**
     * 成功响应
     */
    protected function success($data = [], string $message = '操作成功', int $code = 1): Response
    {
        return $this->response($code, $message, $data);
    }

    /**
     * 失败响应
     */
    protected function error(string $message = '操作失败', int $code = -1, $data = []): Response
    {
        return $this->response($code, $message, $data);
    }

    /**
     * 统一响应格式
     */
    protected function response(int $code, string $message, $data = []): Response
    {
        $result = [
            'code' => $code,
            'message' => $message,
            'result' => $data,
            'timestamp' => time(),
        ];

        // 添加请求追踪ID（如果存在）
        if ($traceId = $this->request->header('X-Trace-Id')) {
            $result['trace_id'] = $traceId;
        }

        return json($result);
    }

    /**
     * 分页响应
     */
    protected function paginate($data, int $total, int $page, int $pageSize): Response
    {
        return $this->success([
            'data' => $data,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize,
            'total_pages' => ceil($total / $pageSize),
        ]);
    }

    /**
     * 获取当前用户ID
     */
    protected function getUserId(): int
    {
        return $this->userInfo->id ?? 0;
    }

    /**
     * 获取当前用户OpenID
     */
    protected function getOpenid(): string
    {
        return $this->userInfo->openid ?? '';
    }

    /**
     * 获取当前用户信息
     */
    protected function getUserInfo()
    {
        return $this->userInfo;
    }

    /**
     * 获取分页参数
     */
    protected function getPaginationParams(): array
    {
        $page = max(1, (int)$this->request->param('page', 1));
        $pageSize = max(1, min(100, (int)$this->request->param('page_size', 10)));
        
        return [$page, $pageSize];
    }

    /**
     * 获取排序参数
     */
    protected function getSortParams(array $allowedFields = []): array
    {
        $sortField = $this->request->param('sort_field', 'id');
        $sortOrder = strtolower($this->request->param('sort_order', 'desc'));
        
        // 验证排序字段
        if (!empty($allowedFields) && !in_array($sortField, $allowedFields)) {
            $sortField = 'id';
        }
        
        // 验证排序方向
        if (!in_array($sortOrder, ['asc', 'desc'])) {
            $sortOrder = 'desc';
        }
        
        return [$sortField, $sortOrder];
    }

    /**
     * 记录操作日志
     */
    protected function logOperation(string $action, array $data = []): void
    {
        \app\service\LogService::userOperation('用户操作记录', [
            'user_id' => $this->getUserId(),
            'openid' => $this->getOpenid(),
            'action' => $action,
            'data' => $data,
            'ip' => $this->request->ip(),
            'user_agent' => $this->request->header('User-Agent'),
            'url' => $this->request->url(true),
            'method' => $this->request->method(),
        ]);
    }

    /**
     * 文件上传处理
     */
    protected function handleFileUpload(string $fieldName, array $allowedTypes = []): array
    {
        $file = $this->request->file($fieldName);
        
        if (empty($file)) {
            throw new \Exception('请选择要上传的文件');
        }

        // 验证文件类型
        if (!empty($allowedTypes)) {
            $extension = strtolower($file->getOriginalExtension());
            if (!in_array($extension, $allowedTypes)) {
                throw new \Exception('不支持的文件类型，支持：' . implode(', ', $allowedTypes));
            }
        }

        // 验证文件大小（默认最大10MB）
        $maxSize = 10 * 1024 * 1024;
        if ($file->getSize() > $maxSize) {
            throw new \Exception('文件大小不能超过10MB');
        }

        return [
            'file' => $file,
            'original_name' => $file->getOriginalName(),
            'extension' => $file->getOriginalExtension(),
            'size' => $file->getSize(),
            'mime_type' => $file->getOriginalMime(),
        ];
    }
}
